<?php
namespace app\common\logic;
use think\Model;
use think\Db;


/**
 * 发起砍价逻辑类
 */
class CutdownFollowLogic extends Model
{
    protected $cutdown;
    protected $cutdownFollow;
    protected $cutdownList;

    public function __construct(){
        parent::__construct();
        $this->cutdown = new \app\common\model\Cutdown;
        $this->cutdownFollow = new \app\common\model\CutdownFollow;
        $this->CutdownList = new \app\common\model\CutdownList;

    }

    /**
     * 用户是否能发起新的砍价
     * @param $ids 砍价活动id
     * @param $user_id 发起砍价用户id
     * @return array
     */
    public function canCutNew($ids,$user_id){
        $time_limit = Db::name('cutdown')->where(['id' => $ids])->value('time_limit');

        $data = Db::name('cutdown_follow')->where(['user_id' => $user_id,'cutdown_id'=>$ids,'is_addorder'=>'0'])
            ->order('id desc')->find();

        if(intval($data['createtime']) + intval($time_limit) >= time()){
            //砍价有效期内,不能发起新的砍价
            $cutdownFollow = $this->cutdownFollow->get($data['id']);

            $cutdownFollow->cutdown;
            $cutdownFollow->goods;
            $cutdownFollow->cutdown_list;
            $arr = $cutdownFollow->toArray();

            if($arr['cutdown_list']){
                foreach ($arr['cutdown_list'] as $k => $v){
                    $user = Db::name('user')->find($v['user_id']);
                    $arr['cutdown_list'][$k]['nickname'] = $user['nickname'];
                    $arr['cutdown_list'][$k]['avatar'] = $user['avatar'];

                }

            }
            $arr['yikan'] = ($arr['cutdown']['price'] * 100 - $arr['deal_price'] * 100) / 100;
            $arr['haikekan'] = ($arr['deal_price'] * 100 - $arr['cutdown']['min_price'] * 100) / 100;

            $cha = time() - $data['createtime'];
            ($time_limit - $cha > 0) ? $daojishi = $time_limit - $cha : $daojishi = 0 ;

            $return = [
                'goods_id' => $arr['goods_id'],
                'item_id' => $arr['item_id'],
                'cutdown_follow_id' => $arr['id'],
                'cutdown_id' => $arr['cutdown']['id'],
                'description' => $arr['cutdown']['description'],
                'sales_sum' => $arr['cutdown']['sales_sum'],
                'price' => $arr['cutdown']['price'],
                'image' => $arr['goods']['image'],
                'yikan' => $arr['yikan'],
                'haikekan' => $arr['haikekan'],
                'time_limit' => $arr['cutdown']['time_limit'],
                'cut_count' => $arr['cut_count'],
                'daojishi_text' => $daojishi,
                'cutdownList' => $arr['cutdown_list']

            ];




            return ['code' => 0, 'msg' => '当前有未完成的砍价', 'data' => $return];
        }else{
            return ['code' => 1, 'msg' => '', 'data' => ''];
        }


    }

}